﻿using System.Collections.Generic;
using System.Data.Common;
using Longbow.Caching;
using System.Data;
using System.Linq;
using System;

namespace HuaCheng.DataAccess
{
    /// <summary>
    /// 对字典表的数据库操作
    /// </summary>
    public class DicHelper
    {
        internal const string RetrieveDictsDataKey = "DicHelper-RetrieveDicts";
        /// <summary>
        /// 查询字典表信息
        /// </summary>
        /// <returns></returns>
        public static List<Dicts> RetrieveDict()
        {
            string key = RetrieveDictsDataKey;
            return CacheManager.GetOrAdd(key, k =>
            {
                List<Dicts> dictSet = new List<Dicts>();
                string sql = "select * from dicts";
                DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
                try
                {
                    using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Dicts dict = new Dicts()
                                {
                                    Category = Convert.ToString(reader["category"]),
                                    Name = Convert.ToString(reader["name"]),
                                    Code = Convert.ToString(reader["code"])
                                };
                                dictSet.Add(dict);
                            }
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
                return dictSet;
            }, RetrieveDictsDataKey);
        }
        /// <summary>
        /// 从字典表查询配置
        /// </summary>
        /// <returns></returns>
        public static List<Dicts> RetrieveAllocation()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "配置").ToList());
        }
        /// <summary>
        /// 从字典表查询系统设置
        /// </summary>
        /// <returns></returns>
        public static List<Dicts> RetrieveSystemSet()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置").ToList());
        }
        /// <summary>
        /// 从字典表查询电压最大值
        /// </summary>
        /// <returns></returns>
        public static string RetrieveVolUpper()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "电压最大值").FirstOrDefault() ?? new Dicts() { Code = "5" }).Code;
        }
        /// <summary>
        /// 从字典表查询电压最小值
        /// </summary>
        /// <returns></returns>
        public static string RetrieveVolLower()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "电压最小值").FirstOrDefault() ?? new Dicts() { Code = "0" }).Code;
        }
        /// <summary>
        /// 从字典表查询电流最小值
        /// </summary>
        /// <returns></returns>
        public static string RetrieveCurrLower()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "电流最小值").FirstOrDefault() ?? new Dicts() { Code = "0" }).Code;
        }

        /// <summary>
        /// 从字典表查询电流最大值
        /// </summary>
        /// <returns></returns>
        public static string RetrieveCurrUpper()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "电流最大值").FirstOrDefault() ?? new Dicts() { Code = "100" }).Code;
        }
        /// <summary>
        /// 从字典表查询母线电压
        /// </summary>
        /// <returns></returns>
        public static string RetrieveBusUnderVolt()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "直流母线电压").FirstOrDefault() ?? new Dicts() { Code = "10" }).Code;
        }
        /// <summary>
        /// 从字典表查询倍率
        /// </summary>
        /// <returns></returns>
        public static string RetrieveMagnification()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "倍率").FirstOrDefault() ?? new Dicts() { Code = "10" }).Code;
        }
        /// <summary>
        /// 从字典表查询电池测试
        /// </summary>
        /// <returns></returns>
        public static string RetrieveBatteryTest()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "电池测试").FirstOrDefault() ?? new Dicts() { Code = "1" }).Code;
        }
        /// <summary>
        /// 从字典表查询是否记录跳转条件
        /// </summary>
        /// <returns></returns>
        public static string RetrieveJumpRecord()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "系统设置" && o.Name == "记录跳转条件").FirstOrDefault() ?? new Dicts() { Code = "1" }).Code;
        }
        /// <summary>
        /// 修改系统设置
        /// </summary>
        /// <param name="dicSystemSet"></param>
        public static void UpdateRange(Dicts dicSystemSet)
        {
            if (dicSystemSet == null) throw new ArgumentNullException("dicSystemSet");
            string sql = "update dicts set code=@code where category=@category and name=@name";
            try
            {
                using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
                {
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@code", dicSystemSet.Code));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@category", dicSystemSet.Category));
                    cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@name", dicSystemSet.Name));
                    DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
                }
                CacheManager.Clear(key => key == RetrieveDictsDataKey);
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
        }
        /// <summary>
        /// 本地日志文件地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveLocalLogPath()
        {
            var dicts = RetrieveDict();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + (dicts.Where(o => o.Category == "地址" && o.Name == "本地日志文件").FirstOrDefault() ?? new Dicts() { Code = "\\XingYun\\LogData\\" }).Code;
            return path;
        }
        /// <summary>
        /// 从字典表查询配置文件地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveConfigPath()
        {
            var dicts = RetrieveDict();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + (dicts.Where(o => o.Category == "地址" && o.Name == "配置文件地址").FirstOrDefault() ?? new Dicts() { Code = "\\XingYun\\config.ini" }).Code;
            return path;
        }
        /// <summary>
        /// 从字典表查询节点图片地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveNodeImgPath()
        {
            var dicts = RetrieveDict();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + (dicts.Where(o => o.Category == "地址" && o.Name == "节点图片地址").FirstOrDefault() ?? new Dicts() { Code = "\\XingYun\\Resources\\" }).Code;
            return path;
        }
        /// <summary>
        /// 从字典表查询ip地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveIPPath()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "地址" && o.Name == "ip地址").FirstOrDefault() ?? new Dicts() { Code = "127.0.0.1" }).Code;
        }
        /// <summary>
        /// 从字典表查询端口号
        /// </summary>
        /// <returns></returns>
        public static string RetrievePort()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "端口号" && o.Name == "端口号").FirstOrDefault() ?? new Dicts() { Code = "17002" }).Code;
        }
        /// <summary>
        /// 根据工步名从字典表查询工步类型号
        /// </summary>
        /// <param name="stepName"></param>
        /// <returns></returns>
        public static int RetrieveStepCode(string stepName)
        {
            var dicts = RetrieveDict();
            return Convert.ToInt32((dicts.Where(o => o.Category == "工步类型" && o.Name == stepName).Select(s => s.Code).First()));
        }
        /// <summary>
        /// 根据工步类型号查询工步名
        /// </summary>
        /// <param name="stepCode"></param>
        /// <returns></returns>
        public static string RetrieveStepName(int stepCode)
        {
            var dicts = RetrieveDict();
            return Convert.ToString(dicts.Where(o=>o.Category=="工步类型"&&o.Code == Convert.ToString(stepCode)).Select(s=>s.Name).First());
        }
        /// <summary>
        /// 从字典表查询工步名称
        /// </summary>
        /// <returns></returns>
        public static List<string> RetrieveAllStepName()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "工步类型").Select(s => s.Name).Distinct().ToList());
        }
        /// <summary>
        /// 从字典表里查询工步名称和工步序号
        /// </summary>
        /// <returns></returns>
        public static Dictionary<int, string> RetrieveStepNameType()
        {

            Dictionary<int, string> dictSet = new Dictionary<int, string>();
            string sql = "select code,name from dicts where category=@cate";
            DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
            try
            {
                cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@cate", "工步类型"));
                using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            int key = Convert.ToInt32(reader["code"]);
                            string val = Convert.ToString(reader["name"]);
                            dictSet.Add(key, val);
                        }
                    }
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); }
            return dictSet;
                

        }
        /// <summary>
        /// 从字典表查询跳转条件
        /// </summary>
        /// <returns></returns>
        public static List<string> RetrieveJumpCond()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "跳转条件").Select(s => s.Name).Distinct().ToList());
        }
        /// <summary>
        /// 从字典表查询跳转目标
        /// </summary>
        /// <returns></returns>
        public static List<string> RetrieveJumpTo()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "跳转目标").Select(s => s.Name).Distinct().ToList());
        }
        /// <summary>
        /// 从字典表查询记录条件
        /// </summary>
        /// <returns></returns>
        public static List<string> RetrieveRecordCond()
        {
            var dicts = RetrieveDict();
            return (dicts.Where(o => o.Category == "记录条件").Select(s => s.Name).Distinct().ToList());
        }
        /// <summary>
        /// 通道信息地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveChlInfoPath()
        {
            var dicts = RetrieveDict();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + (dicts.Where(o => o.Category == "地址" && o.Name == "通道信息").FirstOrDefault() ?? new Dicts() { Code = "\\XingYun\\ChannelSerialize\\channelInfo.txt" }).Code;
            return path;
        }
        /// <summary>
        /// 通道锁定地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveChlLockPath()
        {
            var dicts = RetrieveDict();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + (dicts.Where(o => o.Category == "地址" && o.Name == "通道锁定文件").FirstOrDefault() ?? new Dicts() { Code = "\\XingYun\\LockXml\\" }).Code;
            return path;
        }

        /// <summary>
        /// 查询故障名称
        /// </summary>
        /// <returns></returns>
        public static List<string> RetrieveError(bool flag)
        {
            List<string> err = new List<string>();
            var dicts = RetrieveDict();
            if (!flag)
            {
                err = dicts.Where(o => o.Category == "故障状态").Select(s => s.Name).ToList();
            }
            else
            {
                err = dicts.Where(o => o.Category == "故障状态").Select(s => s.Code).ToList();
            }
            return err;
        }
        /// <summary>
        /// 获取菜单权限
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, bool> RetrieveMenuAutho()
        {
            Dictionary<string, bool> menuAutho = new Dictionary<string, bool>();
            var dics = RetrieveDict();
            List<string> menus = dics.Where(o => o.Category == "操作类型").Select(s => s.Code).ToList();
            foreach (string menu in menus)
            {
                menuAutho.Add(menu, false);
            }
            return menuAutho;
        }
        /// <summary>
        /// 动态通道信息地址
        /// </summary>
        /// <returns></returns>
        public static string RetrieveDysChlInfoPath()
        {
            var dicts = RetrieveDict();
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + (dicts.Where(o => o.Category == "地址" && o.Name == "动态通道信息").FirstOrDefault() ?? new Dicts() { Code = "\\XingYun\\ChannelSerialize\\DysChannelInfo.txt" }).Code;
            return path;
        }
    }
}
